package com.wingsboat.IO;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author wangzhong
 * @description: TODO
 * @date 2024/7/23 9:23
 */
public class NioServer {
    public static void main(String[] args) throws IOException {
        List<SocketChannel> channelList = new ArrayList<>();

        //新建 serverSocketChannel---.分配文件描述符fd
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.socket().bind(new InetSocketAddress(9000));

        serverSocketChannel.configureBlocking(false);

        while(true){
            //分配文件描述符
            SocketChannel socketChannel = serverSocketChannel.accept();
            if(null!=socketChannel){
                socketChannel.configureBlocking(false);
                channelList.add(socketChannel);
            }

            Iterator<SocketChannel> iterator = channelList.iterator();
            while(iterator.hasNext()){
                SocketChannel sc = iterator.next();
                ByteBuffer byteBuffer = ByteBuffer.allocate(128);
                int len = sc.read(byteBuffer);
                if(len>0){
                    System.out.println("接收数据"+new String(byteBuffer.array()));
                }else if(len==-1){
                    iterator.remove();
                    System.out.println("客户端断开连接");
                }
            }
        }

    }
}
